package com.szzg10.webservice.chapter5;

import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.BindingType;
import javax.xml.ws.Provider;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.WebServiceProvider;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.http.HTTPBinding;
import javax.xml.ws.http.HTTPException;

@WebServiceProvider
@BindingType(value = HTTPBinding.HTTP_BINDING)
public class TempConvertR implements Provider<Source> {

	@Resource
	private WebServiceContext webServiceContext;
	
	@Override
	public Source invoke(Source source) {
		MessageContext messageContext = webServiceContext.getMessageContext();
		
		String verb = (String)messageContext.get(MessageContext.HTTP_REQUEST_METHOD);
		if(verb.equalsIgnoreCase("GET")) {
			return doGet(messageContext);
		}
		else {
			throw new HTTPException(405);
		}
	}
	
	private Source doGet(MessageContext messageContext) {
		String query_string = (String)messageContext.get(MessageContext.QUERY_STRING);
		
		float f = Float.parseFloat(query_string.trim());
		float f2c = f2c(f);
		float c2f = c2f(f);
		
		List<String> list = new ArrayList<String>();
		list.add(f2c + "C");
		list.add(c2f + "F");
		
		ByteArrayInputStream in = encode_to_stream(list);
		
		return new StreamSource(in);
	}
	
	private float f2c(float t) {
		return 32.0f + (t * 9.0f / 5.0f);
	}
	
	private float c2f(float t) {
		return (5.0f / 9.0f) * (t -32.0f);
	}
	
	private ByteArrayInputStream encode_to_stream(List<String> list) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		XMLEncoder xmlEncoder = new XMLEncoder(out);
		xmlEncoder.writeObject(list);
		xmlEncoder.close();
		
		return new ByteArrayInputStream(out.toByteArray());
	}

}
